package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.*;
import com.example.demo.entity.pojo.Question;
import com.example.demo.entity.pojo.ids;
import com.example.demo.entity.request.StExamQuestionRequest;
import com.example.demo.entity.request.StExamSaveRequest;
import com.example.demo.entity.request.StExamUserRequest;
import com.example.demo.entity.request.StQuestionGenerateRequest;
import com.example.demo.entity.response.StExamResponse;
import com.example.demo.entity.response.StQuestionGenerateResponse;
import com.example.demo.entity.response.StQuestionResponse;
import com.example.demo.mapper.StExamQuestionMapper;
import com.example.demo.mapper.StExamUserMapper;
import com.example.demo.service.impl.StExamServiceImpl;
import com.example.demo.utils.DateTransferUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.simpleframework.xml.Path;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/exam")
public class StExamController extends BaseController{
    @Autowired
    StExamServiceImpl examService;
    @Resource
    StExamQuestionMapper examQuestionMapper;
    @Resource
    StExamUserMapper examUserMapper;

    @PostMapping("/generate")
    public Result<?> generate(@RequestBody StQuestionGenerateRequest request) {
        StQuestionGenerateResponse response = examService.generate(request);
        if (response == null)
            return Result.error("402", "题目好像没那么多");
        return Result.success(response);
    }

    @GetMapping("/list")
    public Result<?> page(@RequestParam(defaultValue = "1") Integer pageNum,
                          @RequestParam(defaultValue = "10") Integer pageSize,
                          @RequestParam Integer type,
                          @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<StExam> wrapper = Wrappers.lambdaQuery();
        if (type != 0)
            wrapper.eq(StExam::getType, type);
        if (StrUtil.isNotEmpty(search))
            wrapper.like(StExam::getTitle, search);
        wrapper.eq(StExam::getDeleted, false);
        Page<StExam> examPage = examService.page(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(examPage);
    }

    @GetMapping("/list1")
    @ApiOperation(value = "查询某用户需要参加的考试")
    public Result<?> page1(@RequestParam(defaultValue = "1") Integer pageNum,
                          @RequestParam(defaultValue = "10") Integer pageSize,
                          @RequestParam(defaultValue = "") Integer userId) {
        if (StrUtil.isEmpty(userId.toString())) return Result.error("401", "缺少用户id");

        LambdaQueryWrapper<StExamUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StExamUser::getUserId, userId);
        List<StExamUser> list = examUserMapper.selectList(wrapper);

        List<StExam> result = new ArrayList<>();
        for (StExamUser item : list) {
            StExam exam = examService.getById(item.getExamId());
            result.add(exam);
        }

        Page<StExam> page = new Page<>(pageNum, pageSize, result.size());
        page.setRecords(result);
        return Result.success(page);
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id){
        StExam exam = examService.getById(id);
        exam.setDeleted(true);
        return Result.success(examService.updateById(exam));
    }

    @GetMapping("/select/{id}")
    public Result<?> select(@PathVariable Integer id) {
        StExam exam = examService.getById(id);
        if (exam == null) return Result.error("404", "找不到该试卷");

        List<StQuestionResponse> list = examService.select(id);

        StExamResponse examResponse = new StExamResponse();
        BeanUtils.copyProperties(exam, examResponse);
        examResponse.setQuestions(list);

        return Result.success(examResponse);
    }

    @PostMapping("/bind")
    @ApiOperation(value = "为试卷绑定需要参加的用户")
    public Result<?> bind(@RequestBody StExamUserRequest request) {
        if (request.getExam_id() == null) return Result.error("401", "缺少试卷id");
        if (request.getUser_id().size() == 0) return Result.error("401", "没选人");

        for (Integer item : request.getUser_id()) {
            LambdaQueryWrapper<StExamUser> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(StExamUser::getExamId, request.getExam_id()).eq(StExamUser::getUserId, item);
            List<StExamUser> list = examUserMapper.selectList(wrapper);
            if (list.size() == 0) {
                StExamUser examUser = new StExamUser();
                examUser.setExamId(request.getExam_id());
                examUser.setUserId(item);
                examUserMapper.insert(examUser);
            } else {
                StExamUser examUser = list.get(0);
                examUser.setExamId(request.getExam_id());
                examUser.setUserId(item);
                examUserMapper.updateById(examUser);
            }
        }
        return Result.success();
    }

    @PostMapping("/save")
    public Result<?> save(@RequestBody StExamSaveRequest request) {
        StExam exam = new StExam();
        if (request.getId() != null) {
            exam = examService.getById(request.getId());
            if (exam == null) {
                return Result.error("404", "这咋搜不到");
            }
            exam.setModifyTime(DateTransferUtil.getNow());
            exam.setModifyUser(getUser().getPeopleName());
        } else {
            exam.setCreateTime(DateTransferUtil.getNow());
            exam.setCreateUser(getUser().getPeopleName());
            exam.setDeleted(false);
        }
        BeanUtils.copyProperties(request, exam);
        return Result.success(examService.saveOrUpdate(exam));
    }

    @PostMapping("/edit")
    public Result<?> editQuestion(@RequestBody StExamQuestionRequest request) {
        if (request.getId() == null)
            return Result.error("401", "这咋没有id");
        StExam exam = examService.getById(request.getId());
        if (exam == null)
            return Result.error("404", "这咋搜不到");

        List<Question> list = request.getQuestions();
        for (Question item : list) {
            LambdaQueryWrapper<StExamQuestion> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(StExamQuestion::getExamId, request.getId())
                    .eq(StExamQuestion::getQuestionId, item.getId());
            List<StExamQuestion> list1 = examQuestionMapper.selectList(wrapper);
            if (list1.size() == 0) {
                StExamQuestion examQuestion = new StExamQuestion();
                examQuestion.setExamId(request.getId());
                examQuestion.setQuestionId(item.getId());
                examQuestionMapper.insert(examQuestion);
            } else {
                StExamQuestion examQuestion = list1.get(0);
                examQuestion.setExamId(request.getId());
                examQuestion.setQuestionId(item.getId());
                examQuestionMapper.updateById(examQuestion);
            }
        }
        return Result.success();
    }
}
